package rsa

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"git.oschina.net/fanbuchi/redpack/conf/rsa/etc"
)



func RsaEncryptBase64(origData []byte) (string, error) {
	ret,err:=RsaEncrypt(origData)
	encodeString := base64.StdEncoding.EncodeToString(ret)
	return encodeString,err
}


func RsaDecryptBase64(origData string) ([]byte, error) {
	data,err:=base64.StdEncoding.DecodeString(origData)
	ret,err:=RsaDecrypt(data)
	return ret,err
}

// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	publicKey,err:=etc.Asset("conf/rsa/pem/rsa_public_key.pem")
	if err!=nil {
		panic(err)
	}

	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	privateKey,err:=etc.Asset("conf/rsa/pem/rsa_private_key.pem")
	block, _ := pem.Decode(privateKey)

	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
